import { Form, Input, Button, App } from 'antd'
import style from './index.module.less'
import api from '@/api'
import { Login as LoginType, ResType } from '@/types/api'
import localStorage from '@/utils/localStorage'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'

/**
 * 邮箱密码登录时的账号和密码：
 * email: chan_chaw@126.com
 * password: 7y8ep1
 * 成功登录后取 userToken:
 * res.data.userToken = "userToken:2364564351654321654"
 */
function Login() {
  const navigate = useNavigate()
  const { message } = App.useApp()
  const [loading, setLoading] = useState(false)
  const onFinish = (values: LoginType.email) => {
    setLoading(true)
    api
      .login(values)
      .then(res => {
        const tmp = res as ResType
        // 成功登录后保存用户 email 和响应来的 userToken
        localStorage.set('userEmail', values.email)
        localStorage.set('userToken', tmp.data.userToken)
        message.success('登录成功！')
        navigate('/welcome')
      })
      .catch(err => {
        console.log('登录时出现异常：', err)
      })
      .finally(() => setLoading(false))
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }

  return (
    <div className={style.login}>
      <div className={style.loginWrapper}>
        <div className={style.title}>系统登录</div>

        <Form
          name='basic'
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <Form.Item<LoginType.email>
            label='用户名'
            name='email'
            rules={[{ required: true, message: '用户名是必填项！' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item<LoginType.email>
            label='密码'
            name='password'
            rules={[{ required: true, message: '密码是必填项！' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Button type='primary' htmlType='submit' block loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
